<!--
 * @author dumeng
 -->
<template>
  <div class="app-container page-classify-page">
    <div class="classify-btn">
      <div class="btn-title">
        <span>分类管理</span>
      </div>
      <div class="btn-btns">
        <el-button
          v-if="!allListIsEdit"
          @click="handleAddClassify"
        >添加分类
        </el-button>
      </div>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      size="mini"
      :indent="30"
      :cell-style="rowStyle"
      :header-cell-style="headerStyle"
    >
      <el-table-column label="分类名称">
        <template slot-scope="scope">
          <template v-if="scope.row.isEdit">
            <el-input
              v-model="scope.row.classifyName"
              class="edit-input"
              :class="[scope.row.parentId != -1 && 'children']"
              size="small"
              :maxlength="15"
            />
            <el-button
              v-if="
                treeLevel > 0 && scope.row.level < treeLevel && !allListIsEdit
              "
              class="addchild-btn"
              size="small"
              type="text"
              @click="addchild(scope.row)"
            >添加子分类</el-button>
          </template>
          <template v-else>
            <span :class="[scope.row.parentId != -1 && 'children']">{{
              scope.row.classifyName
            }}</span>
            <el-button
              v-if="
                treeLevel > 0 && scope.row.level < treeLevel && !allListIsEdit
              "
              class="addchild-btn"
              size="small"
              type="text"
              @click="addchild(scope.row)"
            >添加子分类</el-button>
          </template>
        </template>
      </el-table-column>
      <!--      <el-table-column v-if="activeTab==='XWFL_XWGL'" label="分类图片" header-align="center" width="150">
        <template slot-scope="scope">
          <template v-if="scope.row.isEdit">
            <el-image :src="view + scope.row.imgId" @click.native="fileFlag = 1">
              <div slot="error" style="cursor: pointer;" class="image-slot">
                点击上传
              </div>
            </el-image>
            <image-no-cropper-upload
              v-if="fileFlag === 1"
              ref="imageUpload"
              accept="image/*"
              :limit="1"
              :multiple="false"
              @close="fileFlag = -1"
              @success="
                (id) => {
                  ;(scope.row.imgId = id), (fileFlag = -1)
                }
              "
            >
              <div slot="tip" class="upload-tip">
                <i class="el-icon-info" />
                请上传图片 建议上传尺寸：150px*150px
              </div>
            </image-no-cropper-upload>
          </template>
          <template v-else>
            <el-image :src="view + scope.row.imgId" :preview-src-list="[view + scope.row.imgId]" />
          </template>
        </template>
      </el-table-column>-->
      <el-table-column label="状态" width="200">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="ZT01"
            inactive-value="ZT02"
            @change="changeStatus(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="职工端是否展示" width="200">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isAppVisit"
            active-value="1"
            inactive-value="0"
            @change="changeShow(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="移动" width="200">
        <template slot-scope="scope">
          <el-button
            :disabled="scope.row.isFirst"
            type="text"
            @click="move(scope.row, 'SY')"
          >上移</el-button>
          <el-button
            :disabled="scope.row.isLast"
            type="text"
            @click="move(scope.row, 'XY')"
          >下移</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <template v-if="scope.row.isEdit">
            <el-button
              type="text"
              style="color: #18a5fd; font-size: 14px"
              @click="handleSave(scope.row)"
            >保存</el-button>
            <el-button
              type="text"
              style="color: #18a5fd; font-size: 14px"
              @click="handleCancel(scope.row)"
            >取消</el-button>
          </template>
          <template v-else>
            <el-button
              type="text"
              style="color: #18a5fd; font-size: 14px"
              @click="handleUpdate(scope.row)"
            >编辑</el-button>
          </template>
          <el-button
            type="text"
            style="color: #18a5fd; font-size: 14px"
            @click="handleDel(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import {
  getDictByCode,
  fetchList,
  del,
  insert,
  update,
  updateStatus,
  move
} from './../api/index'
import permission from '@/directive/permission/index.js' // 权限判断指令
export default {
  name: 'exhibCategory',
  directives: { permission },
  filters: {
    formatStatus(val) {
      return val === 0 ? '启用' : val === 1 ? '禁用' : '禁用'
    },
    formatIshot(val) {
      return val === 0 ? '是' : val === 1 ? '否' : '否'
    }
  },
  data() {
    return {
      listLoading: false,
      searchshow: true,
      expandAll: true,
      list: [],
      curEditRow: {},
      allListIsEdit: false, // 分类树是否存在编辑情况，如果存在隐藏所有的添加下级按钮
      sortable: null,
      dict: {
        ZT: []
      },
      treeLevel: ''
    }
  },
  created() {
    // for (const key in this.dict) {
    //   this.getDict(key)
    // }
    // this.getList()
  },
  methods: {
    /**
     * 切换是否在职工端展示
     */
    changeShow(row) {
      if (!row.id) {
        return
      }
      if (!row.isEdit) {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        const params = {
          id: row.id,
          classifyName: row.classifyName,
          status: row.status,
          parentId: row.parentId,
          classifyType: row.classifyType,
          // imgId: row.imgId,
          isAppVisit: row.isAppVisit
        }
        return new Promise((resolve, reject) => {
          update(params).then(() => {
            this.$message({
              message: '处理成功',
              type: 'success',
              duration: 2000
            })
            loading.close()
            this.getList()
          }).catch(error => {
            loading.close()
            this.getList()
            reject(error)
          })
        })
      }
    },
    rowStyle({ row, columnIndex }) {
      if (columnIndex === 0) {
        return {
          textAlign: 'left'
        }
      } else {
        return {
          textAlign: 'center'
        }
      }
    },
    headerStyle({ row, columnIndex }) {
      if (columnIndex === 0) {
        return {
          textAlign: 'left'
        }
      } else {
        return {
          textAlign: 'center'
        }
      }
    },
    /**
     * 分类移动
     */
    move(row, dir) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      return new Promise((resolve, reject) => {
        move({ id: row.id, msg: dir })
          .then(() => {
            this.$message({
              message: '处理成功',
              type: 'success',
              duration: 2000
            })
            loading.close()
            this.getList()
          })
          .catch((error) => {
            loading.close()
            this.getList()
            reject(error)
          })
      })
    },
    /**
     * 切换启用禁用状态
     */
    changeStatus(row) {
      if (!row.id) {
        return
      }
      if (!row.isEdit) {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        return new Promise((resolve, reject) => {
          updateStatus({ id: row.id, status: row.status })
            .then(() => {
              this.$message({
                message: '处理成功',
                type: 'success',
                duration: 2000
              })
              loading.close()
              this.getList()
            })
            .catch((error) => {
              loading.close()
              this.getList()
              reject(error)
            })
        })
      }
    },
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code)
          .then((res) => {
            this.dict[code] =
                  res.data.data && res.data.data.length > 0
                    ? res.data.data[0].list
                    : []
            if (code === 'AREA_ZQ ') {
              this.levelRange(res.data.data[0].list[0].dictRemark)
              this.getList()
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    levelRange(s) {
      const reg = /^\+?[1-9][0-9]*$/
      if (reg.test(s)) {
        this.treeLevel = Number(s)
      } else {
        this.treeLevel = ''
      }
    },
    handleCancel(row) {
      if (row.id) {
        row['classifyName'] = this.curEditRow.classifyName
        row['status'] = this.curEditRow.status
        this.findPathByLeafId(row.id, this.list).isEdit = false
      } else {
        if (row.parentId) {
          this.findPathByLeafId(row.parentId, this.list).children.shift()
        } else {
          this.list.shift()
        }
      }
      this.allListIsEdit = false
    },
    handleUpdate(row) {
      if (this.allListIsEdit) {
        this.$message({
          message: '请先保存新添加分类',
          type: 'warning'
        })
        return
      } else {
        this.allListIsEdit = true
        this.curEditRow = Object.assign({}, row)
        this.findPathByLeafId(row.id, this.list).isEdit = true
      }
    },
    handleSave(row) {
      var obj = {
        id: row.id,
        classifyName: row.classifyName,
        code: row.code,
        status: row.status,
        parentId: row.parentId,
        classifyType: 'AREA_ZQ '
      }
      this.save(obj)
    },
    save(obj) {
      if (!obj.classifyName) {
        this.$message({
          message: '请填写分类名称',
          type: 'warning'
        })
        return
      }
      const pattern = new RegExp(
        "^\\s|[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]|\\s$"
      )
      if (pattern.test(obj.classifyName)) {
        this.$message({
          message: '请勿输入特殊字符或前后空格',
          type: 'warning'
        })
        return
      }
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      if (obj.id) {
        return new Promise((resolve, reject) => {
          update(obj)
            .then(() => {
              this.allListIsEdit = false
              this.$message({
                message: '处理成功',
                type: 'success',
                duration: 2000
              })
              loading.close()
              this.getList()
            })
            .catch((error) => {
              loading.close()
              reject(error)
            })
        })
      } else {
        return new Promise((resolve, reject) => {
          insert(obj)
            .then(() => {
              this.allListIsEdit = false
              this.$message({
                message: '处理成功',
                type: 'success',
                duration: 2000
              })
              loading.close()

              this.getList()
            })
            .catch((error) => {
              loading.close()
              reject(error)
            })
        })
      }
    },
    handleDel(row) {
      if (row.id) {
        this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.del(row.id)
          })
          .catch(() => {
          })
      } else {
        if (row.parentId) {
          this.findPathByLeafId(row.parentId, this.list).children.shift()
        } else {
          this.list.shift()
        }
        this.allListIsEdit = false
      }
    },
    del(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      return new Promise((resolve, reject) => {
        del({ id: id })
          .then(() => {
            loading.close()
            this.$message({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    },
    getList() {
      this.allListIsEdit = false
      this.listLoading = true
      return new Promise((resolve, reject) => {
        fetchList({ classifyType: 'AREA_ZQ' })
          .then((response) => {
            this.listLoading = false
            this.list = this.initData(response.data.data)
          })
          .catch((error) => {
            this.listLoading = false
            reject(error)
          })
      })
    },
    /**
     * 递归增加是否可以上移下移标识
     * @param data
     * @returns {*}
     */
    initData(data, level = 1) {
      data.forEach((item, index) => {
        item['isFirst'] = false
        item['isLast'] = false
        item['isEdit'] = false
        if (index === 0) {
          item['isFirst'] = true
        }
        if (index === data.length - 1) {
          item['isLast'] = true
        }
        item['level'] = level
        if (item.children && item.children.length > 0) {
          return this.initData(item.children, level + 1)
        }
      })
      return data
    },
    addchild(row) {
      this.allListIsEdit = true
      row['_expanded'] = true
      /* let length = ''
      if (row.children) {
        length = row.children.length
      } else {

      }*/
      const obj = {
        id: '',
        classifyName: '',
        status: 'ZT01',
        isFirst: true,
        isLast: true,
        isEdit: true,
        parentId: row.id
      }
      this.findPathByLeafId(row.id, this.list).children.unshift(obj)
    },
    /**
     * 根据id递归查找所在的对象
     * @param data
     * @returns {*}
     */
    findPathByLeafId(leafId, nodes, path) {
      if (path === undefined) {
        path = {}
      }
      for (var i = 0; i < nodes.length; i++) {
        var tmpPath = path
        if (leafId === nodes[i].id) {
          tmpPath = nodes[i]
          return tmpPath
        }
        if (nodes[i].children) {
          var findResult = this.findPathByLeafId(
            leafId,
            nodes[i].children,
            tmpPath
          )
          if (findResult) {
            return findResult
          }
        }
      }
    },
    handleAddClassify() {
      this.allListIsEdit = true
      const list = this.list
      var length = list.length
      const obj = {
        id: '',
        parentId: '',
        classifyName: '',
        status: 'ZT01',
        isEdit: true,
        isFirst: true,
        isLast: true,
        index: length
      }
      list.unshift(obj)
      this.$set(this, 'list', list)
    },
    handleFilter() {
      this.getList()
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
$dark_gray: #bfced6;
.page-classify-page {
  padding: 20px;

  .classify-tab {
    width: 100%;
    margin-bottom: 10px;
    background-color: #fff;
    padding: 0 10px;

    .el-tabs__header {
      margin: 0;
    }
  }

  .classify-btn {
    display: flex;
    height: 46px;
    line-height: 46px;

    .btn-title {
      flex: 1;
      font-size: 16px;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
    }
  }

  .el-table {
    background-color: transparent;

    .cell {
      display: block;
      // align-items: center;
    }

    thead {
      th {
        font-size: 14px;
        font-family: PingFangSC-Regular;
        font-weight: 400;
        color: rgba(166, 166, 166, 1);
      }
    }

    th,
    tr {
      background-color: transparent;
    }

    tbody {
      background-color: #ffffff;
      font-weight: 500;
    }
  }
}
</style>
<style scoped lang="scss">
.drag-handler {
  width: 20px;
  height: 20px;
  cursor: pointer;
  vertical-align: middle;
}

.edit-input {
  padding-right: 80px;

  &.children {
    padding-left: 20px;
  }
}

.addchild-btn {
  position: absolute;
  right: 15px;
  top: 6px;
}
</style>

